/**审批流程主控类
 * @author xiaowei
 * @date 2017年6月12日
 */
Ext.define('App.ux.approval.Main',{
    extend: 'Ext.container.Container',
	requires: [
		'App.ux.approval.Process',
		'App.ux.approval.models.Inititor',
		'App.ux.approval.models.Init',
		'App.ux.approval.models.InititorWindow',
		'App.ux.approval.Utils',
		'App.ux.approval.ProcessTool',
		'App.ux.approval.FloatWindow',
		'App.ux.approval.models.Start'
	],
	xtype: 'approvalMain',
	isOpenController: true, //是否启用流程引擎提供的[自动控制业务表单属性]的功能？默认启用。
	isOpenGetFormProperty: true,//是否启用获取表单属性。默认开启
	controllerXtype: 'window',//业务表单顶层容器对象
	isSubmitTrans: false, //是否需要先提交业务表单成功之后在发流程
    isLoadTaskRecord: true,//是否显示审批记录，默认显示。
	isServerStart: false,//是否是从服务端发起流程
	submitButton:{},//提交按钮
    startSubmitHidden: false,//起草节点是否隐藏提交按钮，默认不隐藏
	isProcessView: false,//是否是流程查看状态，如果为true，那么流程只能看到审批记录和流程图
    readOnly: false,
    isReturnMeConfig:{//驳回时是否返回到本人check框初始属性设置
        checked:false,
        hidden: false,
        disabled:false
    },
	
	baseParams: {
		//processDefinitionKey:"test-jump001",
		//processInstanceId:"",
        //businessKey: "",
	},
	customParams: {
		//name : 'gong',
		//age  : 12
	},
	paramMap: {},
	mainUrl:'activiti/service/assignee/',
	mainRunTimeUrl:'activiti/service/runtime/',
	//接口：（旧方法）提交成功回调方法与submitSuccess功能一样，建议使用submitSuccess
	updateApproval: function(callBack){},
	//接口：（新方法）提交成功回调方法
	submitSuccess: function(callBack){},
	//接口：提交失败回调方法
	submitFailure: function(callBack){},
	//接口：拦截提交按钮的提交动作。
	submitBefore: function(btn){this._submit()},
	//接口：切换事务回调方法
	transChange: function(callBack){},
	//接口：获取初始化数据请求成功，数据返回给业务端对象
	initSuccess: function(callBack){},
	//接口：获取初始化数据请求失败
	initFailure: function(callBack){},
	
	initComponent: function(){
		var me = this;
		this.baseParams = Ext.clone(this.baseParams);
		this.customParams = Ext.clone(this.customParams);
		this.submitButton = Ext.clone(this.submitButton);
		this.paramMap = Ext.clone(this.paramMap);
		
		this.on({
			afterrender: function(th){
				var myMask = new Ext.LoadMask({
					msg    : '正在加载中...',
					target : th
				});
				me.myMask = myMask;
				if(!me.isRequestDone){
					myMask.show();
				}else{
					me.myMask.destroy();
				}
			}
		});
		this._create();
		this.callParent();
		
	},
	_reCreate: function(){
		var myMask = new Ext.LoadMask({
			msg    : '正在加载中...',
			target : this
		});
		this.myMask = myMask;
		myMask.show();
		this.removeAll();
		this._create();
	},
	
	_create: function(){
		var me = this,params = {};
		var variable = this.customParamsToVariables();
		if(this.baseParams){
			params = Ext.apply({},this.baseParams);
		}
		Ext.apply(params, variable);
		params.isLoadTaskRecord = this.isLoadTaskRecord;//是否显示审批记录，默认显示。
		
		Ext.Ajax.request({
			url: me.mainRunTimeUrl + 'getAssigneeInitData',
            params: {dataJson:JSON.stringify(params)},
			success: function(response, opts) {
				var obj = Ext.decode(response.responseText);
				me.isRequestDone = true;
				if(me.myMask){
					me.myMask.destroy();
				}
				
				if(!obj.success){
					me.showToast('获取流程初始化数据失败',obj.errorMessage);
					me.initFailure(obj);
					return;
				}
				if(!obj.data){
					me.showToast('获取流程初始化数据失败','没有获取到流程信息！');
					return;
				}
				me.initSuccess(obj.data);
				
				me.add(me._createItems(obj.data));
			},
			failure: function(response, opts) {
				me.isRequestDone = true;
				me.initFailure(response);
				if(me.myMask){
					me.myMask.destroy();
				}
			}
		});
	},
	
	_setData: function(data){
		this.data = data;
	},
	
	_createItems: function(data){
		if(!Ext.isObject(data)){
			return;
		}
		this._setData(data);
		if(this.isOpenGetFormProperty && this.baseParams.processInstanceId){
			this.getFormProperty();
		}
		return [this._getItemByProcessStatus()];
	},
	
	_getItemByProcessStatus: function(){
		
		var approval =  {
			xtype: 'approvalmodelsStart',
			_data: this.data,
			_isView: this.readOnly,
            isReturnMeConfig:this.isReturnMeConfig,
			updateApproval: this.updateApproval,
            isServerStart: this.isServerStart,
            submitButton: this.submitButton,
            startSubmitHidden: this.startSubmitHidden,
			transChange: this.transChange,
			mainUrl: this.mainUrl,
			mainRunTimeUrl: this.mainRunTimeUrl,
			triggerObj: this.triggerObj,
			baseParams: this.baseParams,
			customParams: this.customParams,
			paramMap: this.paramMap,
            customParamsToVariables: this.customParamsToVariables,
			processInstanceId : this.baseParams.processInstanceId,
			processDefinitionKey : this.baseParams.processDefinitionKey,
			processXtype: this.processXtype,
			submitSuccess: this.submitSuccess,
			submitBefore: this.submitBefore
			
		};

		if(this.isProcessView){
            approval.xtype = 'approvalmodelsProcessView';
            return approval;
		}
		
		if(!this.baseParams.processInstanceId){//表示流程未发起，调用初始化审批流程页面
			approval.xtype = 'approvalmodelsInit';
		}
		
		return approval;
	},
	showToast:function(title,html){
		Ext.toast({
			title : title,
			html : html,
			align : 't',
			closable : true,
			slideInDuration : 150,
			minWidth : 300,
			minHeight : 30
		});
	},

    customParamsToVariables: function(){
        var object = {'variables':this.customParams};
        return object;
    },
	
	//接口：获取属性列表成功时候回调方法，参数：接收带一个参数的方法
	controlTransForm: function(data){
		var me = this, i, temp, name, label;
		//获取顶层容器对象
		var controller = me.up(me.controllerXtype);
		if(this.isOpenController && controller){//自动控制业务表单属性功能开启并且顶层容器对象存在
			for(i=0; i<data.length; i++){
				temp = data[i].id.split('-');
				name = temp[0];
				if(data[i].isWritable && data[i].isReadable){
                    me.isSubmitTrans = true;
				}
				if(temp.length == 2){
					name = temp[0]+ '[name=' + temp[1] +']';
				}
				temp = controller.down(name);
				if(temp){

					temp.setHidden(!data[i].isReadable);
					//temp.setDisabled(!data[i].isReadable);
					temp.setReadOnly(!data[i].isWritable);

					if(temp.allowBlank && data[i].isRequired && temp.fieldLabel && temp.setFieldLabel){//如果配置信息表明该字段必填，该组件当前状态为非必填，那么将该组件设置为必填并添加必填星号
						
						temp.setFieldLabel(temp.fieldLabel + '<span style="color:red;font-weight:bold;">*</span>');
					}
					if(!temp.allowBlank && !data[i].isRequired && temp.fieldLabel && temp.setFieldLabel){//如果配置信息表明该字段非必填，那么将该组件设置为非必填并去掉必填星号
						label = temp.fieldLabel.split('<span')[0];
						temp.setFieldLabel(label);
					}

					if(temp.setAllowBlank){
						temp.setAllowBlank(!data[i].isRequired);
					}
                    temp.allowBlank = !data[i].isRequired;
				}
			}
		}
		
	},
	
	getFormProperty:function(){
		var params, me = this;
		if(this.data && this.data.task && this.data.task.taskId){
			params = {
				taskId: this.data.task.taskId
			};
		}else{
			return;
		}
		Ext.Ajax.request({
			url: me.mainRunTimeUrl + 'getFormPropertyList',
			params: params,
			method: 'POST',
			success: function(response, opts) {
				var obj = Ext.decode(response.responseText);
				if(obj.data){
					me.controlTransForm(obj.data);
				}
			},

			failure: function(response, opts) {
				me.showToast('失败','获取表单属性控制信息失败');
			}
		});
	},
    submit:function () {
        var aprroval_Submit = this.down('button[name=aprroval_Submit]');
        aprroval_Submit.handler(aprroval_Submit);
    },
	getOperatorInfo:function () {
		var approvalProcess = this.down('approvalProcess');
		if(approvalProcess)
        	return approvalProcess._getOperatorInfo();
    }
});